package com.nitty.cash.loop.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.View
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.nitty.cash.loop.R
import com.nitty.cash.loop.base.app.NittyStackManager
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.DialogGuideTabBinding
import com.nitty.cash.loop.databinding.UiNittyTabBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.ui.adapter.NittyTabAdapter
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.factory.NittyTabFactory
import com.nitty.cash.loop.ui.presenter.NittyTabPresenter
import com.nitty.cash.loop.utils.helper.NittyCreditStatusHelper
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import com.nitty.cash.loop.utils.helper.TestDataLibInvoke
import com.nitty.cash.loop.utils.log.NittyLogger
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import org.json.JSONObject

/**
 * Nitty
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:39
 * @Annotation：主页
 */
class NittyTabAct: CommonActivity(), IViewContract.INittyTabView {
    lateinit var binding: UiNittyTabBinding
    var presenter: NittyTabPresenter? = null
    private var tabAdapter: NittyTabAdapter? = null

    lateinit var guideBinding: DialogGuideTabBinding
    var showGuideIndex = 1
    override fun getNittyRootView(): View {
        binding = UiNittyTabBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        setBackExit(true)
        addNittyTabFragmentPage()
        initNittyTabGridView()

        guideBinding = DialogGuideTabBinding.inflate(layoutInflater)
    }

    override fun initNittyListener() {
        binding.tabViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (presenter?.curtIndex == position){
                    return
                }
                presenter?.curtIndex = position
                presenter?.setMainCurrentItemIndex(position)
            }
        })

        guideBinding.tabGuideLayout.setOnClickListener {
            if (showGuideIndex == 2){
                binding.tabParentLayout.removeView(guideBinding.root)
                return@setOnClickListener
            }
            if (showGuideIndex == 1){
                showGuideIndex = 2
                showNittyTabGuideIndex()
            }
        }
    }

    override fun loadNittyData() {
        if (presenter == null){
            presenter = NittyTabPresenter(this)
        }
        val isShowGuide = NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_DIALOG_GUIDE_TAB_SHOW)
        if (isShowGuide){//已显示过
            showNittyLoading()
        } else {
            showNittyTabGuideDialog()
        }
        presenter?.loadMainTabList()
        presenter?.loadAppProcessAction()
        presenter?.loadOrderListAction()

        //上报 HARDWARE、STORE、DEVICE
        TestDataLibInvoke.sycPhoneStateStoreDeviceHardwareData()
    }

    /**
     * 添加页面
     */
    private fun addNittyTabFragmentPage(){
        val pageAdapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = 4
            override fun createFragment(position: Int): Fragment =
                NittyTabFactory.create(position)
        }
        binding.tabViewPager.isUserInputEnabled = true
        binding.tabViewPager.offscreenPageLimit = 4
        binding.tabViewPager.adapter = pageAdapter
    }

    /**
     * 初始化Tab列表
     */
    private fun initNittyTabGridView() {
        binding.tabRecyclerView.layoutManager = GridLayoutManager(getContext(), 4)
        tabAdapter = NittyTabAdapter(binding.tabRecyclerView)
        binding.tabRecyclerView.adapter = tabAdapter
        binding.tabRecyclerView.itemAnimator = DefaultItemAnimator()
        tabAdapter?.setOnItemChildClickListener(CommonOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.tabItemLayout) {//切换item
                binding.tabViewPager.currentItem = position
            }
        })
    }

    override fun showNittyTabList(tabList: ArrayList<JSONObject>) {
        tabAdapter?.data = tabList
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun notifyNittyTabDataChanged(curtIndex: Int) {
        tabAdapter?.notifyDataSetChanged()
    }

    /**
     * 需要校验手机号
     */
    override fun showNittyCheckNumberPage() {
        //授信是否被拒绝
        val creditStatus = NittyProcessHelper.getAuthBeforeRiskStatus()
        val isCreditRejected = NittyCreditStatusHelper.NittyCreditStatusRepository().isCreditRejected(creditStatus)
        if (isCreditRejected){
            return
        }
        //当前栈定是 手机号校验页面 不重复跳转
        if (NittyStackManager.isCurrentActivity(CheckAct::class.java)){
            return
        }
        //是否是审核账号
        val isConfigAccount = NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_IS_CONFIG_ACCOUNT)
        if(isConfigAccount) {//审核账号，直接不走校验
            return
        }
        CheckAct.start(this)
    }

    /**
     * 引导dialog
     */
    private fun showNittyTabGuideDialog(){
//        val guideTabDialog = NittyGuideTabDialog(this)
//        guideTabDialog.setCancelable(false)
//        guideTabDialog.setCanceledOnTouchOutside(false)
//        guideTabDialog.show()

        NittySharedHelper.putNittySharedData(NittySharedKey.NITTY_DIALOG_GUIDE_TAB_SHOW,true)
        binding.tabParentLayout.addView(guideBinding.root)
        val params = guideBinding.tabGuideLayout.layoutParams
        params.width = FrameLayout.LayoutParams.MATCH_PARENT
        params.height = FrameLayout.LayoutParams.MATCH_PARENT
        guideBinding.tabGuideLayout.layoutParams = params
        guideBinding.tabGuideLayout.setBackgroundColor(Color.parseColor("#66000000"))

        showGuideIndex = 1
        showNittyTabGuideIndex()
    }

    private fun showNittyTabGuideIndex(){
        when(showGuideIndex){
            1 -> {
                guideBinding.guideApplyLayout.visibility = View.VISIBLE
                guideBinding.applyItemLayout.visibility = View.VISIBLE

                guideBinding.guideRepayLayout.visibility = View.GONE
                guideBinding.repayItemLayout.visibility = View.INVISIBLE
            }
            2 -> {
                guideBinding.guideApplyLayout.visibility = View.GONE
                guideBinding.applyItemLayout.visibility = View.INVISIBLE

                guideBinding.guideRepayLayout.visibility = View.VISIBLE
                guideBinding.repayItemLayout.visibility = View.VISIBLE
            }
        }
    }

    override fun onNittyPublishEvent(event: NittyEventData) {
        super.onNittyPublishEvent(event)
        NittyLogger.e(">>>>>>>>>>main>>>>>>>>>>>sub event："+event.eventType)
        when(event.eventType){
            NittyEventData.TYPE.NITTY_CREDIT_REFRESH -> {//刷新授信状态
                presenter?.loadNittyCreditStatusAction()
            }
            NittyEventData.TYPE.NITTY_PROCESS_REFRESH -> {//刷新流程
                presenter?.loadAppProcessAction()
            }
            NittyEventData.TYPE.NITTY_ORDER_REFRESH -> {//刷新订单列表
                presenter?.loadOrderListAction()
            }
            NittyEventData.TYPE.NITTY_SHOW_HOME -> {//显示首页
                binding.tabViewPager.currentItem = 0
            }
            NittyEventData.TYPE.NITTY_SHOW_REPAY -> {//待还款
                binding.tabViewPager.currentItem = 1
            }
            else -> {

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        NittyTabFactory.clear()
    }
}